#!/usr/bin/env ts-node
/**
 * FigmaMCPWorkflow 产物执行器
 * 根据 Phase 规范自动生成/校验关键产物，确保“文档即执行”
 *
 * 用法：
 *   ts-node scripts/workflow/enforce-phase-artifacts.ts <ComponentName> [--phase=Phase2] [--force] [--reference UsageTrendsProd]
 */

import * as fs from 'fs';
import * as path from 'path';
import { execSync } from 'child_process';

interface Options {
  componentName: string;
  phases: Set<string>;
  force?: boolean;
  referenceComponent?: string;
}

function parseArgs(): Options {
  const args = process.argv.slice(2);
  if (args.length === 0) {
    console.error('用法: ts-node scripts/workflow/enforce-phase-artifacts.ts <ComponentName> [--phase=Phase2] [--force] [--reference UsageTrendsProd]');
    process.exit(1);
  }

  const componentName = args[0];
  const phases = new Set<string>();
  let force = false;
  let referenceComponent: string | undefined;

  args.slice(1).forEach(arg => {
    if (arg.startsWith('--phase=')) {
      const value = arg.split('=')[1];
      if (value) {
        phases.add(value);
      }
    } else if (arg === '--force') {
      force = true;
    } else if (arg.startsWith('--reference')) {
      const [, ref] = arg.split('=');
      referenceComponent = ref;
    }
  });

  if (phases.size === 0) {
    ['Phase0', 'Phase2', 'Phase3', 'Phase4', 'Phase5'].forEach(p => phases.add(p));
  }

  return { componentName, phases, force, referenceComponent };
}

function runCommand(command: string) {
  console.log(`\n$ ${command}`);
  execSync(command, { stdio: 'inherit' });
}

function readJson(filePath: string) {
  if (!fs.existsSync(filePath)) {
    throw new Error(`文件不存在: ${filePath}`);
  }
  return JSON.parse(fs.readFileSync(filePath, 'utf8'));
}

function ensurePhase0Artifacts(componentName: string, force: boolean) {
  const componentDir = path.join(process.cwd(), componentName);
  const requirementPath = path.join(componentDir, 'phase0/requirement-fields.json');
  const executionContextPath = path.join(componentDir, 'phase0/execution-context.json');

  const requirement = readJson(requirementPath);
  const executionContext = readJson(executionContextPath);

  const componentDefinitionPath = path.join(componentDir, 'phase0/component-definition.json');
  if (force || !fs.existsSync(componentDefinitionPath)) {
    const componentInfo = executionContext.component || {};
    const componentDefinition = {
      componentCode: componentInfo.code || componentName,
      displayName: componentInfo.displayName || componentName,
      group: componentInfo.group || requirement.meta?.groupName?.value || '',
      subGroup: componentInfo.subGroup || requirement.meta?.subGroupName?.value || '',
      platform: componentInfo.platform || 'H5',
      description: requirement.meta?.description?.value || '',
      configArchitecture: {
        fieldNode: Object.keys(requirement.meta || {}),
        contentPanels: ['basicInfo', 'eventReportSetting', 'groupSetting', 'publishInfo'],
        stylePanels: ['titleStyle', 'cardStyle', 'componentStyle'],
        publicStandard: {
          groupSetting: null,
          publishTime: '',
          expireTime: ''
        }
      }
    };
    fs.writeFileSync(componentDefinitionPath, JSON.stringify(componentDefinition, null, 2));
    console.log(`✅ 写入 ${componentDefinitionPath}`);
  }

  const qualityReportPath = path.join(componentDir, 'phase0/quality-report.json');
  if (force || !fs.existsSync(qualityReportPath)) {
    const docCounts = {
      metaFields: Object.keys(requirement.meta || {}).length,
      contentFields: Object.keys(requirement.content || {}).length,
      styleFields: Object.keys(requirement.style || {}).length
    };
    const publicFieldDefaults = ['groupSetting', 'publishTime', 'expireTime'].map(field => ({
      field,
      default: requirement.content?.[field]?.default ?? requirement.meta?.[field]?.default ?? (field === 'groupSetting' ? null : ''),
      source: requirement.content?.[field]?.source || 'assumed'
    }));
    const report = {
      component: componentName,
      timestamp: new Date().toISOString(),
      parameterCheck: {
        figmaUrl: executionContext.figma?.mainUrl ? 'pass' : 'fail',
        documents: executionContext.documents?.solution ? 'pass' : 'fail',
        promptConfig: 'pass'
      },
      documentExtraction: docCounts,
      publicFieldDefaults,
      warnings: [],
      risks: []
    };
    fs.writeFileSync(qualityReportPath, JSON.stringify(report, null, 2));
    console.log(`✅ 写入 ${qualityReportPath}`);
  }
}

function ensurePhase2Artifacts(componentName: string, referenceComponent?: string) {
  runCommand(`node scripts/phase2/generate-field-mapping.js ${componentName}`);
  if (referenceComponent) {
    runCommand(`node scripts/phase2/generate-reference-comparison.js ${componentName} ${referenceComponent}`);
  }
  runCommand(`node scripts/phase2/generate-ui-diff.js ${componentName}`);
}

function ensurePhase3Artifacts(componentName: string) {
  runCommand(`node scripts/phase3/generate-rag-match-details.js ${componentName}`);
  runCommand(`node scripts/phase3/generate-field-type-validation.js ${componentName}`);
}

function ensurePhase4Artifacts(componentName: string) {
  const output = path.join(process.cwd(), componentName, 'phase4/panel-validation.json');
  runCommand(`node scripts/phase4-panel-validation.js ${componentName} --output ${output}`);
}

function ensurePhase5Artifacts(componentName: string) {
  runCommand(`node scripts/phase5/template-compliance-validator.js ${componentName}`);
}

function main() {
  const options = parseArgs();
  console.log(`\n🚀 enforce-phase-artifacts: ${options.componentName}`);
  console.log(`  执行Phase: ${Array.from(options.phases).join(', ')}`);

  if (options.phases.has('Phase0')) {
    ensurePhase0Artifacts(options.componentName, Boolean(options.force));
  }

  if (options.phases.has('Phase2')) {
    ensurePhase2Artifacts(options.componentName, options.referenceComponent);
  }

  if (options.phases.has('Phase3')) {
    ensurePhase3Artifacts(options.componentName);
  }

  if (options.phases.has('Phase4')) {
    ensurePhase4Artifacts(options.componentName);
  }

  if (options.phases.has('Phase5')) {
    ensurePhase5Artifacts(options.componentName);
  }

  console.log('\n✅ enforce-phase-artifacts 完成');
}

main();
